// 定义用户相关的仓库
import { defineStore } from "pinia";
import { reqUserLogin,reqUserInfo } from "@/api/user";
import type {UserData,UserInfoResponseData,UserLoginResponseData,UserInfo} from "@/api/user/type"
import { GET_TOKEN, SET_TOKEN, REMOVE_TOKEN } from "@/utils/user";

const useUserStore = defineStore('User',{
    state:()=>{
        return {
            userInfo: JSON.parse(GET_TOKEN() as string) || {},
            user: {} as UserInfo
        }
    },
    actions:{
        // 用户登录方法
        async userLogin(loginData:UserData) {
            let result:UserLoginResponseData = await reqUserLogin(loginData)
            if(result.code == 200) {
                this.userInfo = result.data
                //本地存储持久化存储用户信息
                SET_TOKEN(JSON.stringify(this.userInfo));
                //返回一个成功的Promise
                return 'ok';
            }else {
                return Promise.reject(new Error(result.msg));
            }
        },
        // 获取用户信息方法
        async getUserInfo(){
            let result = await reqUserInfo(this.userInfo.userName)
            if(result.code == 200){
                this.user = result.data
                this.user.money = Number(result.data.money).toFixed(2)
            }else {
                return Promise.reject(new Error(result.msg));
            }
        },

        // 退出登录方法
        logout() {
            //清空仓库的数据
            this.userInfo = { userName: '', token: '' };
            //清空本地存储的数据
            REMOVE_TOKEN();
        },
    },
    getters:{

    }
});

export default useUserStore;